import { PlusOutlined } from '@ant-design/icons';
import { Button, Drawer, message} from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import { useAccess } from 'umi';

import { getUserList,createUser } from './service'

import type { userListItem,createUseParams } from './data';

const TableList: React.FC = () => {

  const access = useAccess();

  const [createUserModalVisible, createUserModal] = useState(false);
  // const [createPayModalVisible, handlePayModalVisible] = useState(false);
  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<userListItem>();

  const userListColumns: ProColumns<userListItem>[] = [
    {
      title: '用户ID',
      dataIndex: 'id',
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '创建日期',
      hideInSearch: true,
      dataIndex: 'created_at',
    },
    {
      title: '用户组id',
      hideInTable: true,
      dataIndex: 'role_id',
    },
  ]

  const searchConfig = {
    resetText: '重置查询',
    searchText: '查询用户',
  }

  return (
    <PageContainer>
      <ProTable<userListItem>
        headerTitle="用户列表"
        loading={false}
        actionRef={actionRef}
        rowKey="id"
        bordered={true}
        columns={userListColumns}
        pagination={{
          pageSize: 10,
          current: 1
        }}
        toolBarRender={() => [

          !!access.createUser &&
          <Button
            type="primary"
            icon={<PlusOutlined /> }
            onClick={() => {
              createUserModal(true);
            }}
          >
            新增用户
          </Button>,
        ]}
        search={searchConfig}
        request={async (params) => {
          const dataParams = {
            page: params.current,
            limit: params.pageSize,
            username: params.username,
            role_id: params.role_id,
          }
          const res = await getUserList({ ...dataParams });
          return {
            data: res.data.list,
            success: res.code === 200,
            total: res.data.total,
          };
        }}
      />

      {
        !!createUserModalVisible && (
          <ModalForm<createUseParams>
            width={400}
            title={'新增用户'}
            visible={createUserModalVisible}
            onVisibleChange={createUserModal}
            onFinish={
              async (value) => {
                const res = await createUser({ ...value });
                if (res.code === 200) {
                  message.success('添加成功')
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                } else {
                  message.error('添加失败')
                }
                createUserModal(false)
              }
            }
          >
              <ProFormText
                width="md"
                name="username"
                label="用户名"
                tooltip="用户登录名"
                placeholder="请输入用户名"
                rules={[{ required: true, message: '请输入用户名!' }]}
              />
              <ProFormText.Password
                width="md"
                name="password"
                label="密码"
                tooltip="用户登录密码"
                placeholder="请输入密码"
                rules={[{ required: true, message: '请输入密码!' }]}
              />
              <ProFormText.Password
                width="md"
                name="confirm"
                dependencies={['password']}
                label="请确认密码"
                hasFeedback
                placeholder="请输入密码"
                rules={[
                  {
                    required: true,
                    message: '请确认密码!',
                  },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('确认的密码不一致!'));
                    },
                  }),
                ]}
              />
          </ModalForm>
        )
      }

      {currentRow?.id && (
        <Drawer
          width={600}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={true}
        >
          {/* <ProDescriptions<userListItem>
            column={1}
            bordered={true}
            size="small"
            title='购买订单详情'
            request={async (params) => {
              const res = await getOrderInfo({ ...params });
              return {
                data: res.data.info,
              };
            }}
            params={{
              order_id: currentRow?.id,
            }}
            columns={orderColumns as ProDescriptionsItemProps<userListItem>[]}
          /> */}
        </Drawer>
      )}
    </PageContainer>
  );
};

export default TableList;
